from flask import Blueprint, request
from flask_cors import cross_origin
from api.api_utils import catch_api_exception
from api.items import ApiResponseError, api_status_msg
from api.datas.data_api import *
from blockchain.contract import DeliverContract, ReturnContract

admin_bp = Blueprint("admin_api", __name__)


@admin_bp.route('/task_admin_main', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def task_admin_main():
    task = get_task({'status': '即将众筹'})
    task2 = get_task({'status': '众筹失败'})
    task_count = get_task_count()
    not_ready_count = len(task)
    fail_count = len(task2)
    other_count = task_count - not_ready_count - fail_count
    data = {
        'count': {'task_count': task_count, 'fail_count': fail_count, 'not_ready_count': not_ready_count,
                  'other_count': other_count},
        'task': task,

    }
    return data


@admin_bp.route('/task_admin_block', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def task_admin_block():
    block = get_block_by_index()
    data = {
        'block': block,
    }
    return data


@admin_bp.route('/task_admin_touzi', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def task_admin_touzi():
    touzi = get_touzi_list()
    data = {
        'touzi': touzi,
    }
    return data


@admin_bp.route('/task_admin_tousu', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def task_admin_tousu():
    data = get_task_tousu({'status': 1})
    data = {
        'tousu': data,
    }
    return data


@admin_bp.route('/tousu_admin_disable', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def tousu_admin_disable():
    request_params = request.json or request.args
    tousu_id = request_params.get('tousu_id')
    update_tousu(tousu_id, {'status': 0})
    return 'ok'


@admin_bp.route("/task_admin_status", methods=["GET", "POST"])
@cross_origin(supports_credentials=True)
@catch_api_exception()
def task_admin_status():
    request_params = request.json or request.args
    task_id = request_params.get('task_id')
    status = request_params.get('status')
    task = get_task({'task_id': task_id})
    if not task and status not in ['众筹失败', '正在进行', '众筹完成']:
        raise ApiResponseError(extra_msg=api_status_msg.lack_params)
    if status == '正在进行':
        update_task(task_id, {'inputItems.0.status': 1,
                              'inputItems.0.get_price': 0,
                              'status': status})
    else:
        update_task(task_id, {'status': status})

    if status == '众筹失败':
        contract = ReturnContract(status, task[0])
        contract.execute()
    return 'ok'


@admin_bp.route("/lcb_admin_status", methods=["GET", "POST"])
@cross_origin(supports_credentials=True)
@catch_api_exception()
def lcb_admin_status():
    request_params = request.json or request.args
    task_id = request_params.get('task_id')
    status = int(request_params.get('status'))
    lcb_index = int(request_params.get('lcb_index'))
    task = get_task({'task_id': task_id})
    if not task:
        raise ApiResponseError(extra_msg=api_status_msg.lack_params)
    update_task(task_id, {'inputItems.{}.status'.format(lcb_index): status,
                          'inputItems.{}.get_price'.format(lcb_index): 0})

    return 'ok'


@admin_bp.route('/task_admin_lcb', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def task_admin_lcb():
    # status = request_params.get('即将众筹')
    task = get_task({'status': '正在进行'})
    lcb_count = 0
    start_count = 0
    end_count = 0
    lcb_list = []
    for i in task:
        task_id = i.get('task_id')
        task_name = i.get('name')
        lcb_count += len(i.get('inputItems'))
        for index, j in enumerate(i.get('inputItems', [])):
            if j.get('status') == 1:
                start_count += 1
            if j.get('status') == 2:
                end_count += 1
            d = j
            d['task_id'] = task_id
            d['task_name'] = task_name
            d['lcb_index'] = index
            d['user_id'] = i.get('user_id', '')
            lcb_list.append(d)
    other_count = lcb_count - start_count - end_count
    data = {
        'count': {'count': lcb_count, 'start_count': start_count, 'end_count': end_count, 'other_count': other_count},
        'lcb_list': lcb_list,

    }
    return data


@admin_bp.route("/lcb_admin_push_money", methods=["GET", "POST"])
@cross_origin(supports_credentials=True)
@catch_api_exception()
def lcb_admin_push_money():
    request_params = request.json or request.args
    task_id = request_params.get('task_id')
    lcb_index = int(request_params.get('lcb_index'))
    task = get_task({'task_id': task_id})
    if not task:
        raise ApiResponseError(extra_msg=api_status_msg.error_params)
    contract = DeliverContract(task[0], lcb_index)
    res = contract.execute()
    return res

